package com.zhentao.sample;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.clients.producer.ProducerConfig;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {
//    - 生产者发送消息，多个消费者订阅同一个主题，只能有一个消费者收到消息（一对一）
//- 生产者发送消息，多个消费者订阅同一个主题，所有消费者都能收到消息（一对多）

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址      首先连接kafka
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.6.150:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");


        //保证当前消息所有副本保存后  消息发送成功
        properties.put(ProducerConfig.ACKS_CONFIG,"all");

        //重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);

        //消息压缩 降低当前网络传输开销 COMPRESSION_TYPE_CONFIG   snappy  lz4   gzip  三种算法
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");


        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);



        //封装发送的消息
        ProducerRecord<String,String> record = new ProducerRecord<String, String>
//                ("zhentaogyh-topic","key-1001","Hello kafka My name is gaoyuhang");
//                ("zhentaogyh-topic",0,"key-01","你好 卡夫卡");//轮巡
                ("zhentaogyh-topic","你好 卡夫卡");//不指定分区

        //同步发送消息  可能发生阻塞
//        RecordMetadata metadata = producer.send(record).get();
//        System.err.println("偏移量"+metadata.offset());

        //异步发送
        producer.send(record, new Callback() {
            /**
             *
             * @param recordMetadata  消息
             * @param e
             */
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e != null){
                    System.out.println("记录信息到日志表");
                }
                System.err.println(recordMetadata.offset());
            }
        });


        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

}